package com.xiewz.frame;

import com.xiewz.RunHandler;
import com.xiewz.util.WeiBoUtil;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.Iterator;
import java.util.List;

public class RunFrame extends JFrame {

    private final RunHandler[] handlers = new RunHandler[1];

    JPanel mb = new JPanel();
    JTextField inputText = new JTextField();

    JButton b1 = new JButton("替换文本");//设置一个按钮
    JButton b2 = new JButton("移动图片并替换内容");//设置一个按钮
    JButton b3 = new JButton("上传图片到微博图床并替换");//设置一个按钮
    JTextArea infolabel = new JTextArea("拖入文件，开始点击操作");
    JCheckBox checkBox = new JCheckBox();

    public RunFrame() {
        this.setTitle("md便捷小工具");
        this.setSize(543, 443);//窗口的尺寸
        this.setLocation(500, 200);//窗口的位置
        this.setResizable(false);
        this.setBackground(new Color(187, 5, 5));

        mb.setLayout(null);
        mb.setSize(540, 190);
        mb.setBackground(Color.white);
        this.add(mb, BorderLayout.CENTER);

        JPanel inputP = new JPanel();
        JPanel cookieP = new JPanel();
        JPanel infoP = new JPanel();
        JPanel buttonP = new JPanel();
        initCookeiP(cookieP);
        mb.add(inputP);
        mb.add(infoP);
        mb.add(buttonP);
        mb.add(cookieP);
        new DropTarget(inputP, DnDConstants.ACTION_COPY_OR_MOVE, getFileDorp());
        new DropTarget(inputText, DnDConstants.ACTION_COPY_OR_MOVE, getFileDorp());
        new DropTarget(infolabel, DnDConstants.ACTION_COPY_OR_MOVE, getFileDorp());


        inputP.setLayout(null);
        inputP.setBounds(0, 0, 540, 100);
        JLabel inputlabel = new JLabel("markdown文档的绝对路径：                是否覆盖源文件");
        inputlabel.setFont(new Font("微软雅黑", Font.BOLD, 19));

        inputlabel.setBounds(0, 0, 500, 50);
        checkBox.setBounds(500, 0, 40, 50);
        checkBox.setVisible(true);
        checkBox.setSelected(true);
        inputText.setBounds(2, 50, 530, 40);
        inputText.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        inputText.setForeground(new Color(0, 24, 255));

        inputText.setText("这里输入md文件地址");
        inputText.setToolTipText("这里输入md文件地址");
        inputText.setPreferredSize(new Dimension(180, 3));
        inputText.setVisible(true);

        inputP.add(inputlabel);
        inputP.add(checkBox);
        inputP.add(inputText);

        infoP.setBounds(0, 100, 540, 200);
        infoP.setLayout(null);
        infolabel.setVisible(true);
        infolabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        infolabel.setLineWrap(true);
        infolabel.setWrapStyleWord(true);
        infolabel.setEditable(false);
        // 滚动条
        JScrollPane scrollPane = new JScrollPane(infolabel);
        scrollPane.setBounds(2, 0, 530, 200);
        //分别设置水平和垂直滚动条需要时出现
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        infoP.add(scrollPane);

        buttonP.setLayout(null);
        buttonP.setBounds(0, 300, 540, 50);
        b1.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        b2.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        b3.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        // buttonP.setBackground(new Color(105, 18,0));
        b1.setBounds(0, 0, 100, 30);//设置这个按钮的位置
        b2.setBounds(100, 0, 200, 30);//设置这个按钮的位置
        b3.setBounds(300, 0, 200, 30);//设置这个按钮的位置

        b1.setBackground(new Color(0, 178, 238));
        b2.setBackground(new Color(0, 255, 0));
        b3.setBackground(new Color(0, 255, 238));

        buttonP.add(b1);//把按钮加到容器中
        buttonP.add(b2);
        buttonP.add(b3);

        // 绑定事件
        setButtonActionListencer();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口关闭后程序结束
        this.setVisible(true);//窗口可视化
    }

    private void initCookeiP(JPanel cookieP) {
        cookieP.setLayout(null);
        cookieP.setVisible(true);
        cookieP.setBounds(0,350,540,50);
        JLabel text = new JLabel("要上传图片就要输入微博登录的cookie信息：");
        text.setBounds(0,0,520,25);
        text.setFont(new Font("微软雅黑", Font.BOLD, 18));
        text.setForeground(new Color(255,0,0));
        cookieP.add(text);

        JTextField cookeiT = new JTextField();
        cookeiT.setFont(new Font("monospaced", Font.BOLD, 16));
        cookeiT.setBounds(0,24,540,28);
        cookeiT.setText("");
        cookeiT.setToolTipText("在chrome浏览器登录微博，使用F12找到请求信息里的Cookie内容，复制后填入");
        CookieTextListener cookieTextListener = new CookieTextListener();
        cookeiT.getDocument().addDocumentListener(cookieTextListener);
        cookeiT.addKeyListener(cookieTextListener);
        cookieP.add(cookeiT);
    }

    /**
     * 文件拖拽
     * @return
     */
    public DropTargetAdapter getFileDorp() {
        DropTargetAdapter kgd = new DropTargetAdapter() {
            public void drop(DropTargetDropEvent dtde) {
                try {
                    Transferable tf = dtde.getTransferable();
                    if (tf.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                        List lt = (List) tf.getTransferData(DataFlavor.javaFileListFlavor);
                        Iterator itor = lt.iterator();
                        while (itor.hasNext()) {
                            File f = (File) itor.next();
                            inputText.setText(f.getAbsolutePath());
                        }
                        dtde.dropComplete(true);
                    } else {
                        dtde.rejectDrop();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        return kgd;
    }

    private void setButtonActionListencer() {
        // 替换文本
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {//事件响应器，当点击按钮后会执行方法中的代码
                handlers[0] = new RunHandler(inputText.getText());
                init();
                RunHandler handler = handlers[0];
                try {
                    String info = handler.replaceChar();
                    displayMistake("替换结束-" + info, true);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    displayMistake(e1.getMessage(), false);
                }
            }
        });
        //移动图片并替换内容
        b2.addActionListener((e) -> {
            handlers[0] = new RunHandler(inputText.getText());
            init();
            RunHandler handler = handlers[0];
            try {
                handler.moveImgAndReplace(!checkBox.isSelected());
                displayMistake("移动图片并替换内容-结束", true);
            } catch (Exception e1) {
                e1.printStackTrace();
                displayMistake(e1.getMessage(), false);
            }
        });

        //上传图片到微博图床并替换
        b3.addActionListener((e) -> {
            handlers[0] = new RunHandler(inputText.getText());
            init();
            RunHandler handler = handlers[0];
            try {
                handler.upluadWeiboAndReplace(!checkBox.isSelected());
                displayMistake("上传图片到微博图床并替换-结束", true);
            } catch (Exception e1) {
                e1.printStackTrace();
                displayMistake(e1.getMessage(), false);
            }
        });

    }

    private void init() {
        if (!handlers[0].checkPath()) {
            displayMistake("不是md文件路径", false);
            inputText.setText("");
            throw new RuntimeException("不是md文件路径");
        }
    }


    public void displayMistake(String info, Boolean isSuccess) {

        infolabel.setText(info);
        if (isSuccess) {
            infolabel.setForeground(new Color(5, 255, 0));
        } else {
            infolabel.setForeground(new Color(255, 0, 0));
        }
    }

    class CookieTextListener implements DocumentListener, KeyListener {

        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
            // System.out.println("按下按键:"+e.getKeyChar());
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            //这个是得到你键盘输入的内容
            Document doc = e.getDocument();
            String cookieStr = null;
            try {
                cookieStr = doc.getText(0, doc.getLength());
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }
            System.out.println(cookieStr);
            WeiBoUtil.cookie = cookieStr;
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            insertUpdate(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            insertUpdate(e);
        }
    }

}
